package cn.sibu.myroot.listview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import cn.sibu.myroot.R;

public class ActionActivity extends AppCompatActivity implements AbsListView.MultiChoiceModeListener{

    private static final String[] ITEMS={
            "Mom","Dad","Brother","Sister","Uncle","Aunt","Cousin","GrandFarther","GrandMother"
    };
    private ListView mList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //为上下文事件注册一个按钮
        mList = new ListView(this);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item_layout,R.id.list_item_text,ITEMS);
        mList.setAdapter(adapter);
        mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        mList.setMultiChoiceModeListener(this);

        setContentView(mList,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    @Override
    public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
        Log.e("onItemCheckedState","onItemCheckedStateChanged");
            int count  = mList.getCheckedItemCount();
            mode.setTitle(String.format("%d Selected",count));
    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        Log.e("onCreateActionMode","onCreateActionMode");
        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.context_menu,menu);
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        Log.e("onPrepareActionMode","onPrepareActionMode");
        //如果ActionMode一直是无效的,可以在这里做些工作来更新菜单

        return true;
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        Log.e("onActionItemClicked","onActionItemClicked");
        SparseBooleanArray items = mList.getCheckedItemPositions();
        //通过条目的ID得到用户选择的动作
        switch (item.getItemId()){

            case R.id.menu_delete:
                Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();

                break;
            case R.id.menu_edit:
                Log.e("menu_edit","menu_edit");
                break;
            default:
                return false;

        }
        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        Log.e("onDestroyActionMode","onDestroyActionMode");

    }
}
